
package platzerworld.kegeln.common.appengine;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import platzerworld.kegeln.R;
import platzerworld.kegeln.common.appengine.exception.AppEngineException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

/**
 * @author platzerg
 * 
 */
public class RemoteActivity extends Activity {
	private static final String TAG = "RemoteActivity";

	private TextView mStatus;
	private boolean mIsAuthenticated = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.remote);
		mStatus = (TextView) findViewById(R.id.status);

		if (!mIsAuthenticated) {
			// wenn keine Authentifizierung vorliegt Authentifizierung starten
			Intent intent = new Intent(this, AppEngineActivity.class);
			intent.putExtra(AppEngineActivity.APPLICATION_NAME, "kegelverwaltung.appspot.com");
			startActivityForResult(intent, AppEngineActivity.SETUP_AUTHENTICATE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Log.v(TAG, "RemoteActivity.onActivityResult: Request code: " + requestCode + ". Result Code: " + resultCode + ".");
		mIsAuthenticated = true;

		if (requestCode == AppEngineActivity.SETUP_AUTHENTICATE
				&& resultCode == AppEngineActivity.RESULT_OK
				&& null != KegelverwaltungAppEngine.getInstance()) {
			doAuthenticationSucceeded();
		} else {
			doAuthenticationFailed();
		}
	}

	/**
	 * Erfolgreiche Authentifizierung
	 */
	private void doAuthenticationSucceeded() {
		Log.v(TAG, "Authentication successful!.");
		mStatus.setText("Authenticated!");
		testGet();
		testPostKlassen();
	}

	
	private void testGet() {
		KegelverwaltungAppEngine ae = KegelverwaltungAppEngine.getInstance();
		try {
			String result = KegelverwaltungAppEngine.getStringFromHttpResponse(ae.doHttpGet(""));
			mStatus.setText(result);
			Log.d(TAG, "Result for test GET: " + result);
		} catch (AppEngineException e) {
			e.printStackTrace();
			mStatus.setText(e.getMessage());
		}
	}
		
	private void testPostKlassen() {	
		try {
			KegelverwaltungAppEngine ae = KegelverwaltungAppEngine.getInstance();
			ArrayList<NameValuePair> postData = new ArrayList<NameValuePair>();
			
			postData.add(new BasicNameValuePair("typ", "1"));
			String result = KegelverwaltungAppEngine.getStringFromHttpResponse(ae.doHttpPost("/Klassen", postData));
			mStatus.setText(result);
			Log.d(TAG, "Result of test POST: " + result);
		} catch (AppEngineException e) {
			e.printStackTrace();
			mStatus.setText(e.getMessage());
		}
	}

	/**
	 * keine erfolgreiche Authentifizierung!
	 */
	private void doAuthenticationFailed() {
		mStatus.setText("Authentication failed!");
		Log.e(TAG, "Authentication failed!");
	}

}